package co.chuangdian.oflauncher.widgets.system;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import cn.onekit.APP;
import cn.onekit.CALLBACK;
import cn.onekit.CONFIG;
import cn.onekit.JSON;
import cn.onekit.MESSAGE;
import android.widget.ImageView;
import android.widget.LinearLayout;
import co.chuangdian.oflauncher.R;
import co.chuangdian.oflauncher.widgets.WidgetsFragment;
import uc.DragGridView.OnLongPressListener;
import uc.IconGridView;
import uc.IconInfo;
import uc.IconGridViewAdapter;
import uc.allapp.AllAppActivity;

public class AppWidget extends LinearLayout {
	private Activity context;
	private View view;
	private IconGridView iconGridView;
	private PackageManager packageManager;
	private ImageView addButton;

	public AppWidget(Context context) {
		super(context);
		this.context = (Activity) context;
		this.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		init();
	}

	private void init() {
		view = View.inflate(context, R.layout.widget_fastapp, this);
		addButton = (ImageView) view.findViewById(R.id.addButton);
		addButton.setOnClickListener(clickListener);
		packageManager = context.getPackageManager();
		iconGridView = (IconGridView) view.findViewById(R.id.iconGridView);
		iconGridView.parentScrollView = WidgetsFragment.scrollView;
		iconGridView.setOnItemClickListener(listener);
		iconGridView.setOnLongPressListener(longPressListener);
		adapter = new IconGridViewAdapter(getContext(), iconGridView);
		iconGridView.setAdapter(adapter);
		//
		MESSAGE.receive(AllAppActivity.message, AppWidget.this.getClass().getSimpleName(),
				new CALLBACK<Bundle>() {
					@Override
					public void run(boolean isError, Bundle result) {
						JSONArray appIds = JSON.parses(result.getString("appIDs"));
						UpdateData(appIds);
					}

				});
		//
		reloadIcons();
	}

	List<IconInfo> icons = new ArrayList<IconInfo>();
	JSONArray appIDs;
	void reloadIcons() {
		icons.clear();
		JSONObject systemwidgets = JSON.parse(CONFIG.get("systemwidgets"));
		 appIDs = systemwidgets.optJSONArray("apps");
		//
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		for (int i = 0; i < appIDs.length(); i++) {
			String appID = appIDs.optString(i);
			try {
				PackageInfo app = packageManager.getPackageInfo(appID, 0);
				Drawable icon = app.applicationInfo.loadIcon(packageManager);
				icons.add(new IconInfo(appID, (String)app.applicationInfo.loadLabel(packageManager), icon));
			} catch (NameNotFoundException e) {
			}
		}
		adapter.setData(icons);
		iconGridView.updateHeight();
	}

	IconGridViewAdapter adapter;
	private OnLongPressListener longPressListener = new OnLongPressListener() {

		@Override
		public void onLongPress(int index) {
			showUpdateDailog(index);
		}

	};
	public OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// 跳转到选择app界面
			Intent appIntent = new Intent(context, AllAppActivity.class);
			appIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			appIntent.putExtra("receiver", AppWidget.this.getClass().getSimpleName());
			appIntent.putExtra("appIDs", JSON.stringify(appIDs));
			context.startActivity(appIntent);

		}
	};
	private OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			APP.openApp((String)icons.get(position).id);
		}
	};
	
	private void UpdateData(JSONArray appIDs) {

		JSONObject systemwidgets = JSON.parse(CONFIG.get("systemwidgets"));
		try {
			systemwidgets.put("apps", appIDs);
			CONFIG.set("systemwidgets", systemwidgets);

		} catch (JSONException e) {
			e.printStackTrace();
		}
		reloadIcons();
	}

	private void showUpdateDailog(final int i) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("");
		builder.setMessage("是否移除？");
		builder.setPositiveButton("否", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				dialog.dismiss();
			}
		});

		builder.setNegativeButton("是", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				icons.remove(i);
				appIDs.remove(i);
				UpdateData(appIDs);
				((IconGridViewAdapter) iconGridView.getAdapter()).notifyDataSetChanged();
			}
		});

		// 设置取消的监听, 用户点击返回键时会触发
		builder.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				dialog.dismiss();
			}
		});

		builder.show();
	}

	public void setVisible(boolean isShowing) {
		IconGridViewAdapter adapter = ((IconGridViewAdapter) iconGridView.getAdapter());
		adapter.mini = !isShowing;
		iconGridView.updateHeight();
		adapter.notifyDataSetChanged();
	}

}
